package com.sxfq.loansupermarket.backsystem.modular.basicData.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.ISendMessageService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.dao.OfficialDao;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.SearchOfficialInfo;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.OfficialInfo;
import com.sxfq.loansupermarket.backsystem.modular.basicData.service.IOfficialService;
import com.sxfq.loansupermarket.backsystem.modular.weixin.config.WebChatConfig;
import com.sxfq.loansupermarket.backsystem.modular.weixin.entity.WxTokenInfo;
import com.sxfq.loansupermarket.backsystem.modular.weixin.service.impl.MyX509TrustManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class OfficialServiceImpl implements IOfficialService {
    @Autowired
    private OfficialDao dao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ISendMessageService sendMessageService;

    @Autowired
    private SqlMapper sqlMapper;

    @Override
    public List<OfficialInfo> selectPageListByQueryGetMap(Page<OfficialInfo> page, SearchOfficialInfo searchInfo) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        if (StringUtil.isNotEmpty(searchInfo.getKeyword())) {
            params.put("keyword", searchInfo.getKeyword());
        }
        return dao.getQueryPage(page, params);
    }

    public OfficialInfo selectOneById(String OfficialId) {
        String sql = "select * from official_account where id= '" + OfficialId + "'";
        OfficialInfo info = sqlMapper.selectOne(sql, OfficialInfo.class);
        return info;
    }

    public OfficialInfo getPushContent() {
        String sql = "select push_content as pushContent from initial_push_info limit 1";
        OfficialInfo officialInfo = sqlMapper.selectOne(sql, OfficialInfo.class);
        return officialInfo;
    }

    public int updatePushContent(OfficialInfo info) {
        String sql = "update initial_push_info set push_content='" + info.getPushContent() + "'";
        return sqlMapper.update(sql);
    }

    public int sendingContent(OfficialInfo info) throws Exception {
        sendMessageService.sendTextMessage(info.getSendingContent(), info.getOpenId());
        String insql = "INSERT INTO `sending_group_log_info` (`user_id`,`open_id`, `sending_content`) VALUES " +
                "(" + ShiroKit.getUser().getId() + ",'" + info.getOpenId() + "','" + info.getSendingContent() + "');";
        return sqlMapper.insert(insql);
    }

    public int sendingContents(OfficialInfo info) throws Exception {
        String accessToken = getAccessToken();
        String URL = ("https://api.weixin.qq.com/cgi-bin/user/get?access_token=accessToken").replace("accessToken", accessToken);
        JSONObject jsonObject = httpRequest(URL, "GET", null);//发送请求
        // 如果请求成功
        if (null != jsonObject) {
            JSONObject a = jsonObject.getJSONObject("data");
            System.out.println(a);
            JSONArray arrayList = a.getJSONArray("openid");
            for (Object awrray : arrayList) {
                String openId = awrray + "";
                sendMessageService.sendTextMessage(info.getSendingContent(), openId);
            }
            String insql = "INSERT INTO `sending_group_log_info` (`user_id`, `sending_content`) VALUES " +
                    "(" + ShiroKit.getUser().getId() + ",'" + info.getSendingContent() + "');";
            return sqlMapper.insert(insql);
        } else {
            return 0;
        }
    }

    public String getAccessToken() {
        String accessToken = "";
        String getTokenSql = "select access_token as accessToken from wx_parameter_info where app_id='" + redisTemplate.opsForList().index("APPID",0) + "' limit 1";
        WxTokenInfo wxTokenInfo = sqlMapper.selectOne(getTokenSql, WxTokenInfo.class);
        if (wxTokenInfo == null) {
            accessToken = WebChatConfig.getToken(redisTemplate.opsForList().index("APPID",0)+"",redisTemplate.opsForList().index("AppSecret",0)+"").getAccessToken();
            String updTokenSql = "update wx_parameter_info set access_token='" + accessToken + "' where app_id='" + redisTemplate.opsForList().index("APPID",0) + "';";
            sqlMapper.update(updTokenSql);
        } else {
            if ("".equals(wxTokenInfo.getAccessToken()) || "null".equals(wxTokenInfo.getAccessToken())) {
                accessToken = WebChatConfig.getToken(redisTemplate.opsForList().index("APPID",0)+"",redisTemplate.opsForList().index("AppSecret",0)+"").getAccessToken();
                String updTokenSql = "update wx_parameter_info set access_token='" + accessToken + "' where app_id='" + redisTemplate.opsForList().index("APPID",0) + "';";
                sqlMapper.update(updTokenSql);
            }
            accessToken = wxTokenInfo.getAccessToken();
        }
        return accessToken;
    }

    public static com.alibaba.fastjson.JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        com.alibaba.fastjson.JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = com.alibaba.fastjson.JSONObject.parseObject(buffer.toString());
            // jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            System.out.println("Weixin server connection timed out.");
        } catch (Exception e) {
            System.out.println("https request error:{}" + e.getMessage());
        }
        return jsonObject;
    }

    public int insert(OfficialInfo info) {
        String sqlSql = "select id ,keyword from official_account where keyword ='" + info.getKeyword() + "';";
        List<OfficialInfo> officialInfoList = sqlMapper.selectList(sqlSql, OfficialInfo.class);
        if (officialInfoList.size() > 0) {
            return 1;
        } else {
            String sql = "INSERT INTO `official_account` ( `keyword`, `content`,`type`,`time`) VALUES" +
                    "( '" + info.getKeyword().trim() + "','" + info.getContent().trim() + "','" + info.getType().trim() + "','" + DateTimeKit.now() + "');";
            sqlMapper.insert(sql);
            return 0;
        }
    }

    @Transactional
    public void delete(String id) {
        String sql = "delete from official_account where id = '" + id + "'";
        sqlMapper.delete(sql);
    }

    public int update(OfficialInfo info) {
        String sql = "update `official_account` a set a.keyword='" + info.getKeyword() + "', a.content='" + info.getContent() + "',type='" + info.getType() + "'" +
                ",a.time='" + DateTimeKit.now() + "' where id = '" + info.getId() + "';";
        return sqlMapper.update(sql);
    }

    public List<Map<String, Object>> list() {
        String sql = "select id, keyword from official_account order by time asc;";
        return sqlMapper.selectList(sql);
    }
}